#!/usr/bin/env python

import sys
import string
import irccmds
import re

SERVER = "irc.corp.google.com"
PORT = 6667
NICK = "OPBOT"
IDENT = "OPBOT"
REALNAME = "OPBOT"
CHANNEL = "#jaybocc2"
MSGLEN = 8
OWNER = "jaybendon"
COUNT = 1

#sets the irccmd module and the class irccmds() to the variable irc
irc = irccmds.irccmds()
#sets the irccmd module and the class ircparse() to the variable ircparse
ircparse = irccmds.ircparse()

#connects to the irc server and sets the nickname, user identity and joins a channel
def opencon(server, port, nick, ident, realname, channel, owner):
  irc.connect(server, port)
  irc.nick(nick)
  irc.user(ident, server, realname)
  irc.join(channel)

def parseping(a):
  for line in a:
    print line
    line = string.rstrip(line)
    line = string.split(line)

    if  (line[0] == "PING"):
      irc.pong(line[1])

def botcommands(cmd, usr, line):
  if cmd == "QUIT":
    if usr == OWNER:
      irc.privmsg(CHANNEL, "%s is my owner. I will quit now\r\n" % usr)
      irc.quit("Quitting because %s told me to.\r\n" % usr)
      COUNT = 0
    else:
      irc.privmsg(CHANNEL, "You are not my owner.  Command denied.\r\n")
  elif cmd == "OPME":
    irc.op(ircparse.getchan(line), usr)
  else:
    irc.privmsg(CHANNEL, "Invalid command.\r\n")

def mainloop():
  readbuffer = ''
  COUNT = 1
  while COUNT == 1:
    readbuffer = readbuffer + irc.socks.myreceive()
    temp = string.split(readbuffer, "\n")
    readbuffer = temp.pop( )

    parseping(temp)

    for line in temp:
      print "command loop"
      if ircparse.getbotcall(line) == NICK:
#        print "bot called"
#        if ircparse.getcmd(line) == "QUIT" and ircparse.getusr(line) == OWNER:
#          print "owner called quit"
#          irc.privmsg(CHANNEL, "%s is my owner. I will quit now\r\n" % OWNER) irc.quit("Quitting because %s told me to.\r\n" % ircparse.getusr(line))
#        elif ircparse.getcmd(line) == "QUIT" and ircparse.getusr(line) != OWNER:
#          print "non-owner called quit"
#          irc.privmsg(CHANNEL, "You are not my owner.  Command denied.\r\n")
#        else:
#          print "invalid command"
#          irc.privmsg(CHANNEL, "invalid command. \r\n")
        botcommands(ircparse.getcmd(line), ircparse.getusr(line), line)
      else:
        print "bot call failed"

if __name__ == "__main__":
  opencon(SERVER, PORT, NICK, IDENT, REALNAME, CHANNEL, OWNER)
  mainloop()
